package com.seven.commons.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * @author sevenDay
 * @classname ExcelUtils
 * @description: excel导入和导出工具类
 * @date 2018/1/18
 */
public class ExcelUtils {
    /**
     * 导入excel的方法,默认有验证条件
     *
     * @param inputStream 文件流
     * @param pojoClass 转化为的实体类
     * @param params  导入的时候的参数验证[http://easypoi.mydoc.io/#text_197817]
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> ExcelImportResult<T> importExcel(InputStream inputStream, Class<?> pojoClass, ImportParams params) throws Exception {

        if (Objects.isNull(params)) {
            params = new ImportParams();
            params.setNeedVerfiy(true);
        }
        return ExcelImportUtil.importExcelMore(inputStream, pojoClass, params);
    }
    /**
     * 进行excel的导出工具类
     * @param list           需要导出的excel的list集合
     * @param clazz          导出的实体类类型
     * @param title          导出的title
     * @param sheetName      导出的sheetName
     * @param fileName       导出的excel的 名字
     * @param isCreateHeader 是否创建标题
     * @param response       response对象
     * @param errorMsg       出错的时候的json字符串
     */
    public static void exportExcel(List<?> list, Class<?> clazz, String title, String sheetName, String fileName, boolean isCreateHeader, HttpServletResponse response, String errorMsg) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        //创建header
        exportParams.setCreateHeadRows(isCreateHeader);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        if (!Objects.isNull(workbook)) {
            try {
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                /*throw new RuntimeException("上传解析错误");*/
                workbook.write(response.getOutputStream());
                workbook.close();
            } catch (Exception e) {
                //重置excel的情况，显示json的提示代码
                response.reset();
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/json; charset=utf-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    out.write(errorMsg);
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        }
    }
    /**
     * 进行excel的导出工具类
     * @param list           需要导出的excel的list集合
     * @param clazz          导出的实体类类型
     * @param title          导出的title
     * @param sheetName      导出的sheetName
     * @param fileName       导出的excel的 名字
     * @param isCreateHeader 是否创建标题
     * @param errorMsg       出错的时候的json字符串
     */
    public static void exportExcelToPath(List<?> list, Class<?> clazz, String title, String sheetName, String fileName, boolean isCreateHeader, String errorMsg,String filePath) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        //创建header
        exportParams.setCreateHeadRows(isCreateHeader);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        if (!Objects.isNull(workbook)) {
            File savefile = new File(filePath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(filePath+fileName);
                workbook.write(fos);

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }
}